<template>
  <el-drawer
    v-bind="{ modelValue: visible }"
    v-on="{ 'update:modelValue': (val) => emit('update:visible', val) }"
    title="系统通知"
    direction="right"
    :with-header="true"
    :size="360"
    :before-close="beforeClose"
  >
    <div class="notification-drawer">
      <!-- 通知头部 -->
      <div class="notification-header">
        <div class="notification-tabs">
          <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
            <el-tab-pane label="全部" name="all" :lazy="true">
              <template #label>
                <span>全部</span>
                <el-badge :value="allNotificationsCount" :hidden="allNotificationsCount === 0" />
              </template>
            </el-tab-pane>
            <el-tab-pane label="未读" name="unread" :lazy="true">
              <template #label>
                <span>未读</span>
                <el-badge :value="unreadCount" type="primary" :hidden="unreadCount === 0" />
              </template>
            </el-tab-pane>
            <el-tab-pane label="已读" name="read" :lazy="true" />
          </el-tabs>
        </div>
        <el-button
          type="text"
          size="small"
          @click="markAllAsRead"
          :disabled="unreadCount === 0"
        >
          全部已读
        </el-button>
      </div>
      
      <!-- 通知列表 -->
      <div class="notification-list">
        <div v-if="filteredNotifications.length === 0" class="empty-state">
          <el-empty description="暂无通知" />
        </div>
        
        <div
          v-for="notification in filteredNotifications"
          :key="notification.id"
          class="notification-item"
          :class="{ 'unread': !notification.isRead }"
          @click="handleNotificationClick(notification)"
        >
          <!-- 通知图标 -->
          <div class="notification-icon">
            <el-icon :size="20">
              <component :is="getNotificationIcon(notification.type)" />
            </el-icon>
          </div>
          
          <!-- 通知内容 -->
          <div class="notification-content">
            <div class="notification-title">
              <span>{{ notification.title }}</span>
              <el-badge v-if="!notification.isRead" type="primary" :hidden="notification.isRead" />
            </div>
            <div class="notification-message">{{ notification.message }}</div>
            <div class="notification-time">{{ formatTime(notification.timestamp) }}</div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="notification-actions">
            <el-button
              v-if="!notification.isRead"
              type="text"
              size="small"
              @click.stop="markAsRead(notification.id)"
            >
              已读
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="filteredNotifications.length > 0" class="notification-footer">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :small="true"
          layout="total, prev, pager, next, jumper"
          :total="filteredNotifications.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Warning, 
  InfoFilled, 
  SuccessFilled, 
  CircleClose, 
  Bell, 
  Message, 
  StarFilled 
} from '@element-plus/icons-vue'
import apiService from '../services/apiService.js'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close', 'update:visible'])

// 通知数据 - 模拟数据
const notifications = ref([])

// 标签页状态
const activeTab = ref('all')

// 分页状态
const currentPage = ref(1)
const pageSize = ref(10)

// 计算未读通知数量
const unreadCount = computed(() => {
  return notifications.value.filter(n => !n.isRead).length
})

// 计算所有通知数量
const allNotificationsCount = computed(() => {
  return notifications.value.length
})

// 根据当前标签页过滤通知
const filteredNotifications = computed(() => {
  let filtered = [...notifications.value]
  
  if (activeTab.value === 'unread') {
    filtered = filtered.filter(n => !n.isRead)
  } else if (activeTab.value === 'read') {
    filtered = filtered.filter(n => n.isRead)
  }
  
  // 按时间倒序排序
  filtered.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 获取通知图标
const getNotificationIcon = (type) => {
  switch (type) {
    case 'warning':
      return Warning
    case 'success':
      return SuccessFilled
    case 'error':
      return CircleClose
    case 'info':
      return InfoFilled
    case 'message':
      return Message
    case 'favor':
      return StarFilled
    default:
      return Bell
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const now = new Date()
  const time = new Date(timestamp)
  const diffInSeconds = Math.floor((now - time) / 1000)
  
  if (diffInSeconds < 60) {
    return '刚刚'
  } else if (diffInSeconds < 3600) {
    return `${Math.floor(diffInSeconds / 60)}分钟前`
  } else if (diffInSeconds < 86400) {
    return `${Math.floor(diffInSeconds / 3600)}小时前`
  } else if (diffInSeconds < 2592000) {
    return `${Math.floor(diffInSeconds / 86400)}天前`
  } else {
    return time.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  }
}

// 初始化路由
const router = useRouter()

// 处理通知点击
const handleNotificationClick = (notification) => {
  try {
    if (!notification.isRead) {
      markAsRead(notification.id)
    }
    
    // 处理通知点击事件，例如跳转到相关页面
    if (notification.link) {
      // 跳转到相关链接
      router.push(notification.link)
      emit('close')
    }
  } catch (error) {
    console.error('处理通知点击失败:', error)
    ElMessage.error('处理通知失败')
  }
}

// 标记单条通知为已读
const markAsRead = async (id) => {
  const notification = notifications.value.find(n => n.id === id)
  if (notification && !notification.isRead) {
    notification.isRead = true
    ElMessage.success('已标记为已读')
    
    // 调用API更新后端状态
    try {
      await apiService.markNotificationAsRead(id)
    } catch (error) {
      console.error('更新后端通知状态失败:', error)
    }
  }
}

// 标记所有通知为已读
const markAllAsRead = async () => {
  notifications.value.forEach(notification => {
    if (!notification.isRead) {
      notification.isRead = true
    }
  })
  ElMessage.success('已将所有通知标记为已读')
  
  // 调用API更新后端状态
  try {
    await apiService.markAllNotificationsAsRead()
  } catch (error) {
    console.error('更新后端所有通知状态失败:', error)
  }
}

// 处理标签页切换
const handleTabClick = () => {
  currentPage.value = 1
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 处理分页页码变化
const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 关闭前处理
const beforeClose = (done) => {
  emit('close')
  done()
}

// 监听visible变化，获取通知列表
watch(() => props.visible, (newVal) => {
  if (newVal) {
    loadNotifications()
  }
})

// 加载通知列表
const loadNotifications = async () => {
  try {
    // 调用API获取通知列表
    const response = await apiService.getNotifications()
    notifications.value = response.data || []
    
    // 如果API返回空数据，使用模拟数据
    if (notifications.value.length === 0) {
      notifications.value = [
        {
          id: '1',
          title: '扫描任务完成',
          message: '您的网站安全扫描任务已完成，发现2个潜在漏洞需要关注。',
          type: 'warning',
          timestamp: new Date(Date.now() - 3600000).toISOString(), // 1小时前
          isRead: false,
          link: '/scan-results/123'
        },
        {
          id: '2',
          title: '系统更新提醒',
          message: 'VulnGuard AI系统已更新至最新版本v2.1.0，新增XSS漏洞检测功能。',
          type: 'info',
          timestamp: new Date(Date.now() - 7200000).toISOString(), // 2小时前
          isRead: false,
          link: '/system-updates'
        },
        {
          id: '3',
          title: '扫描计划执行',
          message: '您设置的每日自动扫描计划已成功执行。',
          type: 'success',
          timestamp: new Date(Date.now() - 86400000).toISOString(), // 1天前
          isRead: true,
          link: '/schedules'
        },
        {
          id: '4',
          title: '漏洞修复提醒',
          message: '您有3个高危漏洞已经超过7天未修复，建议尽快处理。',
          type: 'error',
          timestamp: new Date(Date.now() - 172800000).toISOString(), // 2天前
          isRead: true,
          link: '/vulnerabilities/high-risk'
        },
        {
          id: '5',
          title: '新功能上线',
          message: '攻击路径分析功能已正式上线，点击查看详情。',
          type: 'info',
          timestamp: new Date(Date.now() - 259200000).toISOString(), // 3天前
          isRead: true,
          link: '/features/attack-path'
        }
      ]
    }
  } catch (error) {
    ElMessage.error('获取通知列表失败')
    console.error('获取通知列表失败:', error)
    
    // 出错时使用模拟数据
    if (notifications.value.length === 0) {
      notifications.value = [
        {
          id: '1',
          title: '扫描任务完成',
          message: '您的网站安全扫描任务已完成，发现2个潜在漏洞需要关注。',
          type: 'warning',
          timestamp: new Date(Date.now() - 3600000).toISOString(),
          isRead: false,
          link: '/scan-results/123'
        }
      ]
    }
  }
}

// 组件挂载时加载通知
onMounted(() => {
  if (props.visible) {
    loadNotifications()
  }
})
</script>

<style scoped>
.notification-drawer {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.notification-tabs {
  flex: 1;
}

.notification-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.2s;
}

.notification-item:hover {
  background-color: #f8f9fa;
  padding-left: 8px;
}

.notification-item.unread {
  background-color: #f0f7ff;
}

.notification-icon {
  margin-right: 12px;
  padding-top: 2px;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
  margin-bottom: 4px;
  color: #303133;
}

.notification-message {
  font-size: 13px;
  color: #606266;
  margin-bottom: 4px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-actions {
  margin-left: 8px;
}

.notification-footer {
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.empty-state {
  padding: 60px 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>